package cn.xingzhe.monster.user.infrastructure.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.xingzhe.monster.user.domain.exception.UserNotFoundException;
import cn.xingzhe.monster.user.domain.repository.RoleRepository;
import cn.xingzhe.monster.user.domain.repository.UserRepository;
import cn.xingzhe.monster.user.domain.service.PermissionDomainService;
import cn.xingzhe.monster.user.domain.model.RoleModel;
import cn.xingzhe.monster.user.domain.model.UserModel;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * sa-token 权限接口实现类
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final PermissionDomainService permissionDomainService;

    public StpInterfaceImpl(UserRepository userRepository,
                            RoleRepository roleRepository,
                            PermissionDomainService permissionDomainService) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.permissionDomainService = permissionDomainService;
    }

    /**
     * 返回指定账号 id 所拥有的权限码集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        String userId = String.valueOf(loginId);
        return permissionDomainService.getUserPermissionCodes(userId);
    }

    /**
     * 返回指定账号 id 所拥有的角色码集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 角色码集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        String userId = String.valueOf(loginId);
        UserModel user = userRepository.findById(userId)
                .orElseThrow(() -> UserNotFoundException.byId(userId));

        if (user.getRoleIds() == null || user.getRoleIds().isEmpty()) {
            return new ArrayList<>();
        }

        List<RoleModel> roles = roleRepository.findByIds(user.getRoleIds());
        return roles.stream()
                .map(RoleModel::getRoleCode)
                .collect(Collectors.toList());
    }
}

